// 工具函数 - 用于数据转换（CommonJS 版本）

function underscoreToCamel(obj) {
  if (!obj || typeof obj !== 'object') {
    return obj;
  }

  if (Array.isArray(obj)) {
    return obj.map(item => underscoreToCamel(item));
  }

  const result = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      const camelKey = key.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
      result[camelKey] = underscoreToCamel(obj[key]);
    }
  }
  return result;
}

function camelToUnderscore(obj) {
  if (!obj || typeof obj !== 'object') {
    return obj;
  }

  if (Array.isArray(obj)) {
    return obj.map(item => camelToUnderscore(item));
  }

  const result = {};
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      const underscoreKey = key.replace(/([A-Z])/g, '_$1').toLowerCase();
      result[underscoreKey] = camelToUnderscore(obj[key]);
    }
  }
  return result;
}

function formatPaginationData(data, total, page, pageSize) {
  return {
    records: data,
    total: total,
    page: page,
    pageSize: pageSize,
    totalPages: Math.ceil(total / pageSize)
  };
}

function formatResponse(code, message, data = null, meta = undefined) {
  const res = {
    code: code,
    message: message,
    data: data
  };
  if (meta !== undefined) {
    res.meta = meta;
  }
  return res;
}

function toSeconds(expiresIn) {
  if (typeof expiresIn === 'number') return expiresIn;
  const str = String(expiresIn).trim();
  const num = parseInt(str, 10);
  if (Number.isNaN(num)) return 0;
  const unit = str.slice(String(num).length).trim() || 's';
  switch (unit) {
    case 'ms': return Math.floor(num / 1000);
    case 's': return num;
    case 'm': return num * 60;
    case 'h': return num * 3600;
    case 'd': return num * 86400;
    case 'w': return num * 7 * 86400;
    case 'y': return num * 365 * 86400;
    default: return num;
  }
}

module.exports = {
  underscoreToCamel,
  camelToUnderscore,
  formatPaginationData,
  formatResponse,
  toSeconds
};